import { deepTree } from "@/utils";
// 假的 menus 数据
import mockMenus from "@/utils/menus";
import { login, logout, getUserInfo } from "@/api/user";
import store2 from "store2";
import router from "@/router";

export default {
  namespaced: true,

  state: {
    isAdd: false, // 用户是否已经动态添加过路由
    token: store2.get("token") || "", // 用户token
    info: null, // 用户信息
    menus: [], // 用户有权限的菜单数据
    /**
     * 用户有权限的路由路径集合
     *    ['/dashboard/console']
     */
    routes: [],

    /**
     * 用户的按钮权限标识集合
     *    ['base:sys:user:add', 'base:sys:user:delete']
     */
    permissions: [],
  },

  mutations: {
    setIsAdd(state, payload) {
      state.isAdd = payload;
    },
    setToken(state, payload) {
      state.token = payload;
      store2.set("token", payload);
    },
    setInfo(state, payload) {
      state.info = payload;
    },
    setMenus(state, payload) {
      state.menus = payload;
    },
    setRoutes(state, payload) {
      state.routes = payload;
    },
    setPermissions(state, payload) {
      state.permissions = payload;
    },
  },

  actions: {
    /**
     * 登录动作
     */
    async login({ commit }, payload) {
      const data = await login(payload);
      // 1. 将 data.token 写入 store
      commit("setToken", data.token);

      return data;
    },

    /**
     * 登出动作
     */
    async logout({ commit }, flag = true) {
      // 调用接口
      flag && (await logout());
      // 清理数据
      commit("setIsAdd", false);
      store2.clearAll();
      // 跳转路由
      router.replace("/login");
    },

    /**
     * 获取个人信息动作
     */
    async getPerson({ commit }) {
      const data = await getUserInfo();
      commit("setInfo", data.info);
      // 一个假数据
      // data.menus = mockMenus;
      // 过滤掉 type = 2 的 按钮菜单
      const list = data.menus.filter((item) => item.type !== 2);
      commit("setMenus", deepTree(list));

      // 过滤出 type = 1 的
      // 映射出 router 字段
      const routes = data.menus
        .filter((item) => item.type === 1)
        .map((item) => item.router);
      commit("setRoutes", routes);

      // 过滤出 type = 2 的，映射出 perms 字段，做一个数组扁平化
      const perms = data.menus
        .filter((item) => item.type === 2)
        .map((item) => item.perms.split(","))
        .flat();
      commit('setPermissions', perms)

      return data.menus.filter((item) => item.type === 1);
    },
  },
};
